<?php
require_once "settings.inc";
require_once "rtvFunctions.inc";
require_once "parsers.inc";
require_once "renderer.inc";

$channelId   = $_GET['id'];
$channelName = $_GET['name'];
$channelLogo = $_GET['logo'];
$epgDate     = isset($_GET['epgDate']) ? $_GET['epgDate'] : NOW_TIME;

function combineTime($program, $date) {
    if (! isset($program) || ! isset($program->beginTime)) {
        return $date;
    }
    $t = explode(":", $program->beginTime);
    return mktime($t[0], $t[1], 0, date("n", $date), date("j", $date), date("Y", $date));
}

$functions = new RtvFunctions();
$program = $functions->getEpg($channelId, $epgDate);

$parser = new ProgramsParser();
$parser->parse($program);

$selectedIndex = 0;
foreach ($parser->programs as $program) {
    # move cursor if program is in past
    if (combineTime($program, $epgDate) <= $epgDate) {
        $selectedIndex++;
    }
}

# index is zero based
if ($selectedIndex > 0) {
    $selectedIndex--;
}

print drawEpgPage($channelId, $channelName, $channelLogo, $epgDate, 
    $parser->programs, $selectedIndex);

?>
